﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using tusdotnet;
using tusdotnet.Interfaces;
using tusdotnet.Models;
using tusdotnet.Models.Configuration;
using tusdotnet.Stores;

namespace TxtSearch.Webapi.ExtendModule
{
    /// <summary>
    /// 处理文件的上传和下载 还需要完善
    /// </summary>
    public static class HttpTusFileDeal
    {
        /// <summary>
        /// 大文件传输功能tus协议接受文件
        /// </summary>
        /// <param name="app"></param>
        public static void AddTus(this IApplicationBuilder app)
        {
            var savePath = Path.Combine(AppContext.BaseDirectory, "temps");
            Directory.CreateDirectory(savePath);
            app.UseTus(httpContext => Task.FromResult(httpContext.RequestServices.GetService<DefaultTusConfiguration>()));
        }
        public static DefaultTusConfiguration CreateTusConfiguration()
        {
            var savePath = Path.Combine(AppContext.BaseDirectory, "temps");
            return new DefaultTusConfiguration
            {
                // This method is called on each request so different configurations can be returned per user, domain, path etc.
                // Return null to disable tusdotnet for the current request.
                Store = new TusDiskStore(savePath, true, null, new Md5FileIdProvider()),
                // On what url should we listen for uploads?
                UrlPath = "/files",
                Events = new Events
                {
                    OnFileCompleteAsync = async eventContext =>
                    {
                        ITusFile file = await eventContext.GetFileAsync();
                        var filename = Guid.NewGuid().ToString();
                        Dictionary<string, Metadata> metadata = await file.GetMetadataAsync(eventContext.CancellationToken);
                        if (metadata.ContainsKey("filename"))
                        {
                            filename = metadata["filename"].GetString(System.Text.Encoding.UTF8);
                        }
                        using Stream content = await file.GetContentAsync(eventContext.CancellationToken);
                        using FileStream fileStream = File.Create(Path.Combine(savePath, filename));
                        await content.CopyToAsync(fileStream);
                    },
                    OnBeforeCreateAsync = atx =>
                    {
                        if (atx.Metadata.ContainsKey("filename"))
                        {
                            //var file = await atx.Store.FileExistAsync(atx.FileId, atx.CancellationToken);//
                        }
                        //atx.FailRequest(HttpStatusCode.OK,"文件已经存在");//
                        return Task.CompletedTask;
                    }
                }
            };
        }
        /// <summary>
        /// 使用上传的文件名作为文件ID,未上传使用雪花ID
        /// </summary>
        /// <seealso cref="ITusFileIdProvider" />
        public class Md5FileIdProvider : ITusFileIdProvider
        {
            public Task<string> CreateId(string metadata)
            {
                return Task.FromResult(LdtCommonUtil.ObjectId.GenerateNewStringId());
            }

            public Task<bool> ValidateId(string fileId)
            {
                return Task.FromResult(true);
            }
        }
    }
}
